"""
PaddleOCR API 客户端示例
演示如何使用API进行OCR识别
"""

import requests
import json
from typing import Dict, Any, Optional
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class OCRAPIClient:
    """OCR API客户端"""
    
    def __init__(self, base_url: str = "http://localhost:5000"):
        """
        初始化API客户端
        
        Args:
            base_url: API服务基础URL
        """
        self.base_url = base_url.rstrip('/')
        self.api_base = f"{self.base_url}/api/v1"
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json',
            'User-Agent': 'OCR-API-Client/1.0'
        })
    
    def health_check(self) -> Dict[str, Any]:
        """
        健康检查
        
        Returns:
            Dict[str, Any]: 健康检查结果
        """
        try:
            response = self.session.get(f"{self.api_base}/health", timeout=10)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"健康检查失败: {str(e)}")
            raise
    
    def get_service_info(self) -> Dict[str, Any]:
        """
        获取服务信息
        
        Returns:
            Dict[str, Any]: 服务信息
        """
        try:
            response = self.session.get(f"{self.api_base}/info", timeout=10)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"获取服务信息失败: {str(e)}")
            raise
    
    def recognize_text(self, image_url: str) -> Dict[str, Any]:
        """
        识别图片中的文字
        
        Args:
            image_url: 图片URL
            
        Returns:
            Dict[str, Any]: OCR识别结果
        """
        try:
            data = {"image_url": image_url}
            response = self.session.post(
                f"{self.api_base}/ocr",
                json=data,
                timeout=120  # OCR可能需要较长时间
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"OCR识别失败: {str(e)}")
            raise
    
    def extract_text_only(self, image_url: str) -> str:
        """
        仅提取识别的文字内容
        
        Args:
            image_url: 图片URL
            
        Returns:
            str: 识别的文字内容
        """
        result = self.recognize_text(image_url)
        
        if not result.get('success'):
            return ""
        
        texts = []
        for res in result.get('data', {}).get('results', []):
            if res.get('complete_text'):
                texts.append(res['complete_text'])
        
        return " ".join(texts)
    
    def print_recognition_result(self, result: Dict[str, Any]) -> None:
        """
        打印识别结果
        
        Args:
            result: OCR识别结果
        """
        if not result.get('success'):
            print(f"❌ 识别失败: {result.get('error', '未知错误')}")
            return
        
        data = result.get('data', {})
        print(f"✅ 识别成功!")
        print(f"📷 图片URL: {data.get('image_url', '')}")
        print(f"⏰ 识别时间: {data.get('timestamp', '')}")
        
        # 图片信息
        image_info = data.get('image_info', {})
        if image_info:
            print(f"📊 图片信息: {image_info.get('width', 0)}x{image_info.get('height', 0)} "
                  f"({image_info.get('format', 'Unknown')})")
        
        # 统计信息
        stats = data.get('statistics', {})
        print(f"📈 统计信息: {stats.get('total_text_segments', 0)} 段文字, "
              f"{stats.get('result_groups', 0)} 个结果组")
        
        # 识别结果
        results = data.get('results', [])
        for i, res in enumerate(results, 1):
            print(f"\n📝 结果组 {i}:")
            print(f"   完整文本: {res.get('complete_text', '')}")
            print(f"   段落数量: {res.get('total_segments', 0)}")
            
            # 统计信息
            stats = res.get('statistics', {})
            if stats:
                print(f"   平均置信度: {stats.get('average_confidence', 0)}%")
                print(f"   高置信度段落: {stats.get('high_confidence_segments', 0)}")
            
            # 详细段落
            segments = res.get('segments', [])
            if segments:
                print("   详细段落:")
                for seg in segments:
                    print(f"     {seg.get('index', 0)}. {seg.get('text', '')} "
                          f"(置信度: {seg.get('confidence', 0)}%)")

def main():
    """主函数 - 演示API使用"""
    print("=" * 70)
    print("🚀 PaddleOCR API 客户端示例")
    print("=" * 70)
    
    # 创建客户端
    client = OCRAPIClient()
    
    try:
        # 1. 健康检查
        print("1. 健康检查...")
        health = client.health_check()
        if health.get('success'):
            print("✅ 服务运行正常")
        else:
            print("❌ 服务异常")
            return
        
        # 2. 获取服务信息
        print("\n2. 获取服务信息...")
        info = client.get_service_info()
        if info.get('success'):
            service_data = info.get('data', {})
            print(f"✅ 服务名称: {service_data.get('service_name', '')}")
            print(f"   版本: {service_data.get('version', '')}")
            print(f"   支持格式: {', '.join(service_data.get('supported_formats', []))}")
        
        # 3. OCR识别示例
        print("\n3. OCR识别示例...")
        
        # 示例图片URL列表
        example_urls = [
            # 这里可以添加实际的图片URL进行测试
            "https://raw.githubusercontent.com/PaddlePaddle/PaddleOCR/release/2.6/doc/imgs/11.jpg",
            # "https://example.com/your-image.jpg"
        ]
        
        for i, url in enumerate(example_urls, 1):
            print(f"\n📷 测试图片 {i}: {url}")
            try:
                result = client.recognize_text(url)
                client.print_recognition_result(result)
            except Exception as e:
                print(f"❌ 识别失败: {str(e)}")
        
        print("\n" + "=" * 70)
        print("🎉 示例演示完成!")
        print("=" * 70)
        
    except Exception as e:
        print(f"❌ 客户端错误: {str(e)}")

if __name__ == "__main__":
    main()
